#ifndef __WEBSOCKET_HANDLER__
#define __WEBSOCKET_HANDLER__

#include <iostream>
#include <map>
#include <sstream>
#include "../core/codebase64.h"
#include "sha1.h"
#include "../inc/logger.h"
#include "websocket_request.h"
#include <event2/bufferevent.h>
#include <event2/buffer.h>

#define MAGIC_KEY "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
using namespace std;

enum WEBSOCKET_STATUS {
	WEBSOCKET_UNCONNECT = 0,
	WEBSOCKET_HANDSHARKED = 1,
};

enum WS_FrameType
{
	WS_EMPTY_FRAME = 0xF0,
	WS_ERROR_FRAME = 0xF1,
	WS_TEXT_FRAME = 0x01,
	WS_BINARY_FRAME = 0x02,
	WS_PING_FRAME = 0x09,
	WS_PONG_FRAME = 0x0A,
	WS_OPENING_FRAME = 0xF3,
	WS_CLOSING_FRAME = 0x08
};

typedef std::map<std::string, std::string> HEADER_MAP;

class Websocket_Handler{
public:
	Websocket_Handler(int fd);
	~Websocket_Handler();
	int process(struct evbuffer *evbuf,string& retStr);
	int encodeMsg(const string& msg, string& outStr);
	inline char *getbuff();
private:
	int handshark(const string& data, string& outStr);
	void parse_str(char *request);
	int fetch_http_info(const string& data);
	int decodeFrame(const string& inFrame, string &outMessage);
	int encodeFrame(const string& inMessage, string &outFrame, enum WS_FrameType frameType);
public:
	int sendMsg(const string& msg);
	int send_data(const string& data);
	bool isConnected(){ return status_ == WEBSOCKET_HANDSHARKED;  }
private:
	//char buff_[10240];
	WEBSOCKET_STATUS status_;
	HEADER_MAP header_map_;
	int fd_;
};

//inline char *Websocket_Handler::getbuff(){
//	return buff_;
//}

#endif
